export function base64ToFile(base64Data, type = 1, filename = `${new Date().getTime()}.png`) {
	// 将base64的数据部分提取出来
	const parts = base64Data.split(';base64,');
	const contentType = parts[0].split(':')[1];
	const raw = window.atob(parts[1]);
	const rawLength = raw.length;
	const uInt8Array = new Uint8Array(rawLength);

	for (let i = 0; i < rawLength; ++i) {
		uInt8Array[i] = raw.charCodeAt(i);
	}

	// 使用Blob和提取出的数据以及文件名创建一个新的File对象
	const blob = new Blob([uInt8Array], {
		type: contentType
	});
	const file = new File([blob], filename, {
		type: contentType
	});

	return type === 1 ? file : blob;
}

import domToImage from 'dom-to-image';
export async function svgToPng(id = "svg", options = {}) {
	let { scale = 4, allowTaint = false, useCORS = true, width = '100', height = '100', backgroundColor = null } = options
	let idDom = document.getElementById(id);
	width = (Number((window.getComputedStyle(idDom).width).replace('px', '')));
	height = (Number((window.getComputedStyle(idDom).height).replace('px', '')));

	await domToImage.toBlob(idDom, { quality: 1, bgcolor: '#ffffff', width, height, scale: 2 }).
	then(async (dataUrl) => await clipboard(dataUrl, 1)).
	catch((error) => ElMessage({ message: '图片生成失败', type: 'warning' }));

	// let { scale = 3, allowTaint = false, useCORS = true, width = '100', height = '100', backgroundColor = null } = options
	// const el = document.getElementById(id);
	// width = (Number((window.getComputedStyle(el).width).replace('px', '')));
	// height = (Number((window.getComputedStyle(el).height).replace('px', '')));

	// 	let base64 = canvas.toDataURL('image/png');
	// 	let file = base64ToFile(base64, 2);
	// 	await clipboard(file, 1);
	// } catch (err) {
	// 	ElMessage({ message: '图片转换失败', type: 'warning', })
	// }
}

export async function clipboard(e, type = 1) {
	if (e) {
		try {
			if (type === 1) {
				await navigator.clipboard.write([new ClipboardItem({
					[e.type]: e,
				})]);
			} else {
				await navigator.clipboard.writeText(e);
			}
			ElMessage({ message: '复制成功', type: 'success' })
		} catch (err) {
			ElMessage({ message: '此浏览器不支持复制Api', type: 'warning', })
		}
	} else {
		ElMessage({ message: '内容不能为空', type: 'warning', })
	}
}
